package com.app.couponsharelife.ui.main.me.experiencemen
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.view.View
import cn.sharesdk.framework.Platform
import cn.sharesdk.framework.PlatformActionListener
import cn.sharesdk.framework.ShareSDK
import cn.sharesdk.wechat.friends.Wechat
import cn.sharesdk.wechat.moments.WechatMoments
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.dialog.BotShareDialog
import com.app.couponsharelife.ui.dialog.SXBindingPhoneDialog
import com.app.couponsharelife.ui.listener.OnClickListener
import com.app.couponsharelife.ui.main.me.phonenum.BindPhoneNumActivity
import com.app.couponsharelife.utils.AppUtils
import com.app.couponsharelife.utils.WhiteToast
import com.tencent.smtt.sdk.*
import com.tencent.smtt.utils.TbsLog
import kotlinx.android.synthetic.main.activity_experiencemen.*
import java.util.HashMap

/**
 *Created by xct on 2019/1/19
 *Description:体验官说明页面
 */
class ExperienceMenActivity:BaseActivity() {
    private var gradeID=""
    private var userPhone=""
    private var type="0"
    private var url=""
    private var name=""
    private var requestcode=""
    private var webSettings:WebSettings?=null
    override val viewLayoutId: Int
        get() = R.layout.activity_experiencemen
    override fun initViews() {
        AppUtils.initImmersionBar(this,false)
        //AppUtils.setString(Contacts.INVITATION_CODE, it.data.data!!.requestcode?:"")
        requestcode=AppUtils.getString(Contacts.INVITATION_CODE,"")
        type=intent.getStringExtra("Type")?:"0"
        setBG()
        gradeID=AppUtils.getString(Contacts.USER_GRADE_ID,"0")
        experiencemen_ivClose.setOnClickListener { onBackPressed() }
        experiencemen_llshare.setOnClickListener {
            //showShare()
            BotShareDialog(this, R.style.DialogStyle, object : OnClickListener {
                override fun click(arg1: Int, arg2: Any) {
                    showShare(arg1)
                }
            }).show()
        }
        experiencemen_llgoumai.setOnClickListener {
            setSXIntent()
        }
        /*experiencemen_but.setOnClickListener {
            when(type){
                "0"->{setSXIntent()}
                "1"->{setJJIntent()}
            }
        }*/
        initWebView()
    }
    private fun setBG(){
        when(type){
            "0"->{

            }
            "1"->{

            }
        }
    }
    private fun setBindPhoneDialog(){
        SXBindingPhoneDialog(this,R.style.DialogStyle,object : OnClickListener {
            override fun click(arg1: Int, arg2: Any) {
                val intent=Intent(this@ExperienceMenActivity, ExperienceMenPayActivity::class.java)
                intent.putExtra("Type","CEO")
                startActivity(intent)
            }
        }).show()
    }
    private fun setSXIntent(){
        if (gradeID.toLong() <4) {  //vip和svip
            userPhone=AppUtils.getString(Contacts.USER_MOBILE,"")
            if (userPhone.isEmpty()){
                /*val intent=Intent(this, BindPhoneNumActivity::class.java)
                intent.putExtra("Type","Choiceness")
                startActivity(intent)*/
                setBindPhoneDialog()
            }else{
                //startActivity(Intent(this, ExperienceMenActivity::class.java))
                val intent=Intent(this, ExperienceMenPayActivity::class.java)
                intent.putExtra("Type","CEO")
                startActivity(intent)
            }
        }else{  //是首席
            showToastMsg("当前账户等级不符合购买条件！")
            //WhiteToast.getInstance().showToast("当前账户等级不符合购买条件！")
        }
    }
    private fun setJJIntent(){
        ///startActivity(Intent(this,ExperienceCurriculumActivity::class.java))
        if (gradeID.toLong()<3||gradeID=="4") {
            userPhone=AppUtils.getString(Contacts.USER_MOBILE,"")
            if (userPhone.isEmpty()){
                val intent=Intent(this, BindPhoneNumActivity::class.java)
                intent.putExtra("Type","Cooperation")
                startActivity(intent)
            }else{
                //startActivity(Intent(this, ExperienceMenActivity::class.java))
                startActivity(Intent(this,ExperienceCurriculumActivity::class.java))
            }
        }else{  //是首席
            //showToastMsg("当前账户等级高于首席体验官或不符合购买条件，无法购买！")
            WhiteToast.getInstance().showToast("当前账户等级不符合购买条件，无法购买！")
        }
    }
    private fun initWebView() {
        url=intent!!.getStringExtra("url")?:"http://www.yiyepay.cn/buyMember/index.html?openTime="+System.currentTimeMillis()
        showProgressDialog("请稍候")
        experiencemen_mWebView.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                if (newProgress == 100) {
                    dismissProgressDialog()
                    experiencemen_mWebView.visibility = View.VISIBLE
                }
                super.onProgressChanged(view, newProgress)
            }
        }
        experiencemen_mWebView.webViewClient = object : WebViewClient() {
            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                super.onPageStarted(view, url, favicon)
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
            }

            override fun shouldOverrideUrlLoading(p0: WebView?, url: String?): Boolean {
                /*if (url!=null&&url.isNotEmpty()){
                    if (url.startsWith("http") || url.startsWith("https") || url.startsWith("ftp")){
                        Log.e("eee","常规链接---->${url}")
                        //http://127.0.0.1:12345/error?code=fdWuTuXdwFgZHQ8smRnueUlB4290749&state=1212
                        if (url.startsWith("https://detail")||url.startsWith("https://uland")){
                            //goTaoBao(url)
                            return true
                        }else{
                            return super.shouldOverrideUrlLoading(p0, url)
                        }
                    }else{
                        if (url.startsWith("tbopen://")){
                            return true
                        }else{
                            Log.e("eee","AppUri---->${url}")
                            var intent: Intent?=null
                            try {
                                intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME)
                            } catch (e: URISyntaxException) {
                                return false
                            }
                            intent.setComponent(null)
                            try {
                                startActivity(intent)
                            } catch (e: ActivityNotFoundException) {
                                return false
                            }
                            return true
                        }
                    }
                }else{*/
                    return super.shouldOverrideUrlLoading(p0, url)
                /*}*/
            }
        }
        setWebString(url)
    }
    private fun setWebString(mIntentUrl:String){
        webSettings=experiencemen_mWebView.settings
        webSettings!!.allowFileAccess = true
        webSettings!!.layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS
        webSettings!!.setSupportZoom(true)
        webSettings!!.builtInZoomControls = true
        webSettings!!.useWideViewPort = true
        webSettings!!.setSupportMultipleWindows(false)
        // webSetting.setLoadWithOverviewMode(true);
        webSettings!!.setAppCacheEnabled(true)
        // webSetting.setDatabaseEnabled(true);
        webSettings!!.domStorageEnabled = true
        webSettings!!.setJavaScriptEnabled(true)
        webSettings!!.setGeolocationEnabled(true)
        webSettings!!.setAppCacheMaxSize(java.lang.Long.MAX_VALUE)
        webSettings!!.setAppCachePath(this.getDir("appcache", 0).path)
        webSettings!!.databasePath = this.getDir("databases", 0).path
        webSettings!!.setGeolocationDatabasePath(this.getDir("geolocation", 0)
                .path)
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSettings!!.pluginState = WebSettings.PluginState.ON_DEMAND
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        // webSetting.setPreFectch(true);
        val time = System.currentTimeMillis()
        experiencemen_mWebView.loadUrl(mIntentUrl)
        TbsLog.d("time-cost", "cost time: " + (System.currentTimeMillis() - time))
        CookieSyncManager.createInstance(this)
        CookieSyncManager.getInstance().sync()
    }

    private fun showShare(shareType:Int) {
        //"http://www.yiyepay.cn/buyMember/index_h5.html?openTime ="+System.currentTimeMillis()
        if (requestcode.isEmpty()){
            showToastMsg("获取邀请码出错，请退出重试！")
            return
        }
        val shareUrl="http://mp.yiyepay.cn/q11api/home/OauthUser?url=http://www.yiyepay.cn/buyMember/index_h5.html&invitationCode=$requestcode"
        val sp= Platform.ShareParams()
        sp.shareType= Platform.SHARE_WEBPAGE
        sp.imageData=BitmapFactory.decodeResource(resources,R.drawable.imag_sx_share)
        sp.title="券享生活AI机器人手机"
        sp.text="人工智能/轻奢创业/拓客神器/变现机器/自动赚钱的AI微信机器人/永享首席体验官权益"
        sp.url=shareUrl
        val wechat = if (shareType == 1){
            ShareSDK.getPlatform (WechatMoments.NAME)
        }else{
            ShareSDK.getPlatform (Wechat.NAME)
        }
        wechat.platformActionListener=object : PlatformActionListener {
            override fun onComplete(p0: Platform?, p1: Int, p2: HashMap<String, Any>?) {
                //Log.e("eeee","--->完成")
            }

            override fun onCancel(p0: Platform?, p1: Int) {
                //Log.e("eeee","--->取消")
            }

            override fun onError(p0: Platform?, p1: Int, p2: Throwable?) {
                //Log.e("eeee","--->${p0?.name}---->${p1}----->${p2!!.message}")
            }
        }
        wechat.share(sp)
    }
    override fun onBackPressed() {
        if (experiencemen_mWebView.canGoBack()) {
            experiencemen_mWebView.goBack()
        } else {
            finish()
        }
    }
    override fun onDestroy() {
        super.onDestroy()
        AppUtils.destroyImmersionBar(this)
    }
}